var unitsNames;
//var destinationUnitsNames;

$(document).on('unitsLoaded profileLoaded', function (e) {
	if (currentProfileId == undefined) {
		return;
	}
	if (units == undefined) {
		return;
	}

    unitsNames = new Array();
    
    $.each(units, function (index, unit) {
        $.each(unit.languages, function (index, value) {
            value.usageCount = unit.usageCount;
            value.id = unit.id;
            value.category = unit.category;
            unitsNames.push(value);
        });
    });


    $(function () {
        $('[id*=source-unit]').each(function () {
            var sourceBox = this;
            var sourceUnit;

            $.each(unitsNames, function (index, unit) {
                if (sourceBox.value.toLowerCase() == this.value.toLowerCase()) {
                    sourceUnit = this;
                }
            });


            addDestinationAutocomplete(sourceUnit, sourceBox);

            $(this).autocomplete({
                minLength: 0,
                source: unitsNames,
                focus: function (event, ui) {
                    return false;
                },
                change: function (event, ui) {
                    if (validateUnitNames(event)) {
                        var box = this;
                        $.each(unitsNames, function (index, unit) {
                            if (box.value.toLowerCase() == unit.value.toLowerCase()) {
                                switchLanguage(unit.lang);
                            }
                        });
                        $('#' + $(this).attr('value-box')).trigger('keyup');
                    }
                },
                response: function (event, ui) {
                    ui.content.sort(sortByFlag).sort(sortByUsage);
                    
                },
                select: function (event, ui) {
                    $(this).val(ui.item.value); 
                    switchLanguage(ui.item.lang);
                    $('#' + $(this).attr('value-box')).trigger('keyup');
                    addDestinationAutocomplete(ui.item, this);

                    return false;
                }
           })
            .data('ui-autocomplete')._renderItem = function (ul, item) {
                return $('<li>')
                     .append(
                               $('<a>').append(
                                    item.value + ' '
                               ).append(
                                    $('span#' + item.lang).clone().attr('id', '')
                               )
                          ).appendTo(ul);
            };
        })
    });

    $('[id*=source-unit]').focusout(validateUnitNames);
    $('[id*=source-unit]').blur(validateUnitNames);

    $('[id*=destination-unit]').focusout(validateUnitNames);
    $('[id*=destination-unit]').blur(validateUnitNames);

});

function addDestinationAutocomplete(sourceUnit, sourceBox) {
    var destinationUnitsNames = new Array();

    $.each(unitsNames, function (index, value) {
        if (value.category == sourceUnit.category && value.id != sourceUnit.id) {
            destinationUnitsNames.push(value);
        }
    });

    $('#' + ($('#' + $(sourceBox).attr('value-box')).attr('dest-box').split(','))).each(function () {
            var destinationBox = this;
            var flag = true;

            $.each(destinationUnitsNames, function (index, unit) {
                if (unit.value.toLowerCase() == $(destinationBox).val().toLowerCase()) {
                    flag = false;
                }
            });

            if(flag)
                $(this).val($(destinationUnitsNames[0]).attr('value'));
    });
    
    $(function () {
        $('#'+($('#' + $(sourceBox).attr('value-box')).attr('dest-box').split(','))).each(function () {
            $(this).autocomplete({
                minLength: 0,
                source: destinationUnitsNames,
                delay: 500,
                focus: function (event, ui) {
                    $(this).val(ui.item.value);
                    $('#' + $('#' + $(this).attr('source-box')).attr('value-box')).trigger('keyup');
                    return false;
                },
                change: function (event, ui) {
                    if (validateUnitNames(event)) {
                        var box = this;
                        $.each(unitsNames, function (index, unit) {
                            if (box.value.toLowerCase() == unit.value.toLowerCase()) {
                                switchLanguage(unit.lang);
                                $(box).parent().find('button').hide();
                                $(box).css('border-bottom-right-radius', '4px');
                                $(box).css('border-top-right-radius', '4px');
                            }
                        });
                        $('#' + $('#' + $(this).attr('source-box')).attr('value-box')).trigger('keyup');
                    }
                },
                search: function (event, ui) {
                    $(this).val($.trim($(this).val()));
                },
                response: function (event, ui) {
                    ui.content.sort(sortByFlag).sort(sortByUsage);
					/* check if unit exists in other category */
                    if (ui.content.length == 0) {
                        var newUnit = {};
                        newUnit.value = $(this).val();
                        newUnit.category = $(this).autocomplete("option", "source")[0].category;
                        var flag = true;
                        $.each(unitsNames, function(index, unit){
                            if(newUnit.value.toLowerCase() == unit.value.toLowerCase()){
                                flag = false;
                            }
                        });
                        if(flag){
                            //show modal dialog to add the unit:
                            $(this).parent().find('button').show().click(function (){
                                $('span#unit-name input').val($('#' + 
                                    $(this).parent().parent().find('input').attr('source-box')
                                ).val());
							
                                $('#customUnitModal').attr('new-unit-name', newUnit.value).attr('new-unit-category',newUnit.category).modal();
                            });
                            $(this).css('border-bottom-right-radius','0');
                            $(this).css('border-top-right-radius','0');
                        } else {
                            //unit already exists in other category hide button
                            $(this).parent().find('button').hide();
                            $(this).css('border-bottom-right-radius','4px');
                            $(this).css('border-top-right-radius','4px');
                        }
                    }
                },
                select: function (event, ui) {
                    $(this).val(ui.item.value);
                    switchLanguage(ui.item.lang);
                    $(this).parent().find('button').hide();
                    $(this).css('border-bottom-right-radius', '4px');
                    $(this).css('border-top-right-radius', '4px');
                    $('#' + $('#' + $(this).attr('source-box')).attr('value-box')).trigger('keyup');
                    return false;
                }
            })
            .data('ui-autocomplete')._renderItem = function (ul, item) {
                return $('<li>')
                     .append(
                               $('<a>').append(
                                    item.value + ' '
                               ).append(
                                    $('span#' + item.lang).clone().attr('id', '')
                               )
                          ).appendTo(ul);
            };
        })
    });

}

function sortByUsage(unit1, unit2) {
    return ((unit1.usageCount < unit2.usageCount) ? -1 : ((unit1.usageCount > unit2.usageCount) ? 1 : 0));
}

function sortByFlag(unit1, unit2) {
    if (unit1.lang == currentLanguageId)
        return -1;

    if (unit2.lang == currentLanguageId)
        return 1;

    return ((unit1.lang < unit2.lang) ? -1 : ((unit1.lang > unit2.lang) ? 1 : 0));
    
}

function validateUnitNames(obj) {
    var unitsValid = true;

    unitsValid &= check(obj.currentTarget);

    destvalboxes = [$('#' + $(obj.currentTarget).attr('value-box'))];
    $.each(destvalboxes[0].attr('dest-value-box').split(), function () {
        destvalboxes.push($('#' + this));
    });
    $(destvalboxes).each(function () {
        unitsValid &= check($('#' + $(this).attr('unit-box')));
    });

    if (unitsValid) {
        $(destvalboxes).each(function () {
            $(this).prop('readOnly', false).trigger('keyup');
        });
    } else {
        $(destvalboxes).each(function () {
            $(this).prop('readOnly', true);
        });
    }

    return unitsValid;
}

function check(obj) {
    if ($(obj).attr('id').indexOf('source') != -1) {
        return SourceUnitNameValidator(obj);
    } else {
        return DestinationUnitNameValidator(obj);
    }
}

function SourceUnitNameValidator(obj) {
    var valid = false;
    $.each(unitsNames, function (index, unit) {
        if ($(obj).val().toLowerCase() == unit.value.toLowerCase()) {
            valid = true;
        }
    });
	return valid;
}

function DestinationUnitNameValidator(obj) {
	var valid = false;
	$.each($(obj).autocomplete("option", "source"), function (index, unit) {
        if ($(obj).val().toLowerCase() == unit.value.toLowerCase()) {
            valid = true;
        }
    });
	return valid;
}